//
//  SettingInputTableViewCell.swift
//  SitPosition
//
//  Created by apple on 2019/4/7.
//  Copyright © 2019 apple. All rights reserved.
//

import Foundation
import UIKit


/**
 * 学习设置：带输入框的Cell
 */
class SettingInputTableViewCell : UITableViewCell, Reuseable {
    
    // 输入变化回调
    public var onInputChanged: (_ newValue: String?) -> Void = { _ in }
    public var value: String? = nil {
        didSet { inputTF.text = value }
    }
    
    // 输入框
    public private(set) lazy var inputTF: UITextField = {
        let tfBounds = CGRect(x: 0, y: 0, width: 100, height: 32)
        let tf = UITextField(frame: tfBounds)
        tf.delegate = self
        tf.borderStyle = .none
        tf.clearButtonMode = .whileEditing
        tf.font = Theme.Font.regularFont(ofSize: 16)
        tf.textColor = Theme.Color.primaryDarkTextColor
        tf.backgroundColor = UIColor.clear
        tf.textAlignment = NSTextAlignment.right
        return tf
    }()
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: UITableViewCell.CellStyle.default, reuseIdentifier: reuseIdentifier)
        selectionStyle = UITableViewCell.SelectionStyle.none
        
        // titleLabel
        textLabel?.font = Theme.Font.mediumFont(ofSize: 16)
        textLabel?.textColor = Theme.Color.primaryDarkTextColor
        textLabel?.lineBreakMode = .byTruncatingTail
        textLabel?.textAlignment = .left
        textLabel?.numberOfLines = 1
        textLabel?.adjustsFontSizeToFitWidth = true
        
        // accessoryView
        accessoryView = inputTF
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

// MARK: - UITextFieldDelegate

extension SettingInputTableViewCell : UITextFieldDelegate {
    
    func textFieldDidEndEditing(_ textField: UITextField) {
        onInputChanged(textField.text)
    }
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }
}
